import {
  HTTP
} from '../../utils/http'
import Toast from '@vant/weapp/toast/toast';
let http = new HTTP()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    myGridShow: false,
    myPictureStyleShow: false,
    myTextCorrelationShow: false,
    myPictureCorrelationShow: false,
    myReferencePictureShow: false,
    shieldingWordsShow: false,
    myPictureStyleModelShow: false,
    trainingDirectionShow: false,
    viewNameShow: false,
    trainingDirectionList: [{
      text: "人物",
      value: 1
    }, {
      text: "其他",
      value: 0
    }],
    fileList: [],
    fileListModel: [],
    nameTemp: "",
    // 关键字textarea最高高度和最小高度
    autosize: {
      maxHeight: '424rpx',
      minHeight: '424rpx'
    },
    // 使用图片switch选中标识
    usePicturesChecked: false,
    // 表单数据json
    formData: {
      keyWord: "", // 关键字
      pictureScale: null, // 生成图片比例(废弃)
      pictureStyle: null, // 图片风格
      textCorrelation: 7.5, //文本相关性
      usePictures: false, //使用图片
      referencePicture: null, //参考图
      pictureCorrelation: 0.7, //图片相关性
      shieldingWords: null, //屏蔽词
      name: "创作盒名称",
      modelImg: [],
      pictureModelStyle: null, //模型训练图片风格
      styleModelId: null, // 模型训练图片风格id
      trainingDirection: null, //训练方向
      trainingDirectionId: null, //训练方向id
      trainingEnglish:null //训练方向英文
    },
    // 图片比例数组
    pictureScaleList: [{
      resolution: '512*512',
      proportion: '1:1',
      width: '162rpx',
      height: '162rpx'
    }, {
      resolution: '512*768',
      proportion: '2:3',
      width: '108rpx',
      height: '162rpx'
    }, {
      resolution: '768*512',
      proportion: '3:2',
      width: '162rpx',
      height: '108rpx'
    }],
    // 图片风格
    pictureStyleList: [{
        imgSrc: "https://img.yzcdn.cn/vant/cat.jpeg",
        name: "动漫"
      },
      {
        imgSrc: "https://img.yzcdn.cn/vant/cat.jpeg",
        name: "普通"
      }
    ]
  },
  onKeyWordChange(e) {
    this.setData({
      "formData.keyWord": e.detail
    })
  },
  // 点击生成创作盒
  onCreateBox(e) {
    let that = this
    let type = e.currentTarget.dataset.type
    let formData = this.data.formData
    let data = {
      /**
       * 模型训练图组
       */
      "images": formData.modelImg,
      /**
       * 创作盒描述
       */
      "description": formData.keyWord,
      /**
       * 文本相关性 0-20，默认7.5
       */
      "guidance": formData.textCorrelation,
      /**
       * 生成表情包高
       */
      "high": 512,
      /**
       * 生成表情包宽
       */
      "width": 512,
      /**
       * 参考图url
       */
      "initImageUrl": formData.referencePicture ? formData.referencePicture : (formData.modelImg ? formData.modelImg[0] : null),
      /**
       * 是否使用图片 0-未使用 1-使用
       */
      "isUsedImage": formData.usePictures ? 1 : 0,
      /**
       * 模型
       */
      "model": formData.pictureStyle ? formData.pictureStyle : formData.pictureModelStyle,
      /**
       * 创作盒名称
       */
      "name": formData.name,
      /**
       * 反向文本
       */
      "negativePrompt": formData.shieldingWords,
      /**
       * 图像变化强度，0-1，默认0.7
       */
      "strength": formData.pictureCorrelation,
      /**
       * 风格id
       */
      "styleId": formData.styleId ? formData.styleId : formData.styleModelId,
      /**
       * 创作盒url
       */
      "url": formData.referencePicture ? formData.referencePicture : (formData.modelImg ? formData.modelImg[0] : null),
      /**
       * 生成盒子类型 0-普通 1-训练
       */
      "type": type,
      /**
       * 训练方向英文
       */
      "trainType": formData.trainingEnglish
    }
    let dataJson = JSON.stringify(data);
    http.request({
      url: '/ai/draw/box/build',
      method: "POST",
      data: data,
      success: (res) => {
        if (res.code === '0') {
          if(type=='1'){
            // 训练盒子直接跳转首页
            wx.navigateTo({
              url: '/pages/box-detail/box-detail?id='+res.data
            })
          }else{
            wx.navigateTo({
              url: '/pages/createBox/createBox?dataJson=' + dataJson
            })
          }
        } else {
          Toast.fail({
            message: res.msg,
            context: that
          });
        }
      }
    })
  },
  // 重命名展示
  onEditName(e) {
    this.setData({
      viewNameShow: true,
      nameTemp: this.data.formData.name
    })
  },
  //重命名确认
  onDoneName(e) {
    this.setData({
      "formData.name": this.data.nameTemp
    })
  },
  //临时名称
  onChangeTempName(e) {
    this.setData({
      nameTemp: e.detail
    })
  },
  onDeleteModelImg(e) {
    this.data.fileListModel.splice(e.currentTarget.dataset.imageIndex, 1);
    this.data.formData.modelImg.splice(e.currentTarget.dataset.imageIndex, 1);
    this.setData({
      fileListModel: this.data.fileListModel,
      "formData.modelImg": this.data.formData.modelImg
    })
  },
  onShieldingWords(e) {
    this.setData({
      shieldingWordsShow: true
    })
  },
  onShieldingWordsDone(e) {
    this.setData({
      "formData.shieldingWords": e.detail.value
    })
  },
  onDoneTrainingDirection(e) {
    // console.log(e);
    this.setData({
      "formData.trainingDirection": e.detail.chinese,
      "formData.trainingDirectionId": e.detail.id,
      "formData.trainingEnglish": e.detail.english
    })
  },
  onMyTextCorrelation(e) {
    this.setData({
      myTextCorrelationShow: true
    })
  },
  onMyPictureStyleModel(e) {
    this.setData({
      myPictureStyleModelShow: true
    })
  },
  onTrainingDirection(e) {
    this.setData({
      trainingDirectionShow: true
    })
  },
  onMyTextCorrelatiDone(e) {
    if (e.detail) {
      this.setData({
        "formData.textCorrelation": e.detail
      })
    }
  },
  onMyPictureCorrelation(e) {
    this.setData({
      myPictureCorrelationShow: true
    })
  },
  onMyPictureCorrelationDone(e) {
    if (e.detail) {
      this.setData({
        myPictureCorrelationShow: false,
        "formData.pictureCorrelation": e.detail
      })
    }
  },
  onUsePicturesChange(e) {
    this.setData({
      "formData.usePictures": !this.data.formData.usePictures
    })
  },
  onMyGrid(e) {
    this.setData({
      myGridShow: true
    })
  },
  myGridOnDone(e) {
    this.setData({
      myGridShow: false,
      'formData.pictureScale': e.detail.value
    })
  },
  onMyReferencePicture(e) {
    this.setData({
      myReferencePictureShow: true
    })
  },
  onMyReferencePictureDone(e) {
    this.setData({
      myReferencePictureShow: false,
      'formData.referencePicture': e.detail
    })
  },
  onMyPictureStyle() {
    this.setData({
      myPictureStyleShow: true
    })
  },
  myPictureStyleOnDone(e) {
    this.setData({
      myPictureStyleShow: false,
      'formData.pictureStyle': e.detail.value.chinese,
      'formData.styleId': e.detail.value.id
    })
  },
  myPictureStyleOnModelDone(e) {
    this.setData({
      myPictureStyleModelShow: false,
      'formData.pictureModelStyle': e.detail.value.chinese,
      'formData.styleModelId': e.detail.value.id
    })
  },
  // 参考图上传
  afterRead(e) {
    let that = this
    http.uploadFile({
      url: '/ai/draw/box/upload/pic',
      filePath: e.detail.file.url,
      name: 'file', //后端接收图片的字段名
      success(res) {
        res = JSON.parse(res)
        if (res.code === '0') {
          const data = res.data
          that.setData({
            fileList: [{
              url: data
            }]
          })
          that.setData({
            "formData.referencePicture": data
          })
        } else {
          Toast.fail({
            message: res.msg,
            context: that
          });
        }
      },
      error(err) {
        Toast.fail({
          message: '图片上传失败!' + err,
          context: that
        });
      }
    })


  },
  // 模型图上传
  afterReadModel(e) {
    this.batchUpload(e.detail.file)
  },

  batchUpload(files) {
    let that = this
    return Promise.all(
      files.map((file, index) => {
        return new Promise((resolve, reject) => {
          http.uploadFile({
            url: '/ai/draw/box/upload/pic',
            filePath: file.url,
            name: 'file', //后端接收图片的字段名
            success(res) {
              res = JSON.parse(res)
              if (res.code === '0') {
                const data = res.data
                that.data.fileListModel.push({
                  url: data
                })
                that.data.formData.modelImg.push(data)
                that.setData({
                  "formData.modelImg": that.data.formData.modelImg,
                  fileListModel: that.data.fileListModel
                })
                resolve(res.data)
              } else {
                reject(res);
                Toast.fail({
                  message: res.msg,
                  context: that
                });
              }
            },
            error(err) {
              Toast.fail({
                message: '图片上传失败!' + err,
                context: that
              });
            }
          })
        }).then(results => {
          if (results) {
            console.log('上传成功')
          }
          // return { urls: results.map(data => data.url) };
        }).catch(err => {
          Toast.fail({
            message: '上传失败重新上传!',
          });
          return Promise.reject(err);
        })
      })
    )
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDictList(0, (data) => {
      this.setData({
        pictureStyleList: data
      })
    })
    this.getDictList(1, (data) => {
      this.setData({
        trainingDirectionList: data
      })
    })
  },

  getDictList(type, success) {
    http.request({
      url: '/ai/draw/dict/get/list',
      method: "GET",
      data: {
        type
      },
      success: (res) => {
        let data = res.data;
        success && success(data)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})